<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Orderlist extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->load->model('Orderlist_m', 'm');
        $this->load->model('Order_m', 'order');
        $this->pageSize = $this->config->item('pagenum');
    }

    public function index()
    {
        $this->tpl->display("product/welcome.tpl");
    }

    /******订单列表*******/
    public function orderlist()
    {
		$t1 = microtime(true);
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
		
		$kw = trim($this->input->get_post('kw'));
		if($kw)
		{
			 $where.= "";
		}else{
			 if (intval($this->input->get_post('status'))==7) {
			 }else{
				 $where = " AND order_status !=7";
			 }
		}

        //批量搜索
        $batchsearch = $this->input->get_post('batchsearch');
        if($batchsearch){
	        $flagtype = trim($this->input->get_post("flagtype"));
			$istype = trim($this->input->get_post("istype"));
	        if($flagtype==1){
		        $conn = "";
		       

				if($istype==2)
				{
					$arr_batch  = explode("\n",$batchsearch);
					foreach($arr_batch as $key=>$value){
						if(trim($value)){
							$conn.=trim($value).",";
						}
					}
					$conn = trim($conn,",");
					$rsdb = $this->db->get_one("SELECT GROUP_CONCAT(mabangorderid) as mabang from db_factory_order where orderId in($conn)");
					$where.=" AND order_sn in($rsdb[mabang])";
				}else{
					 $arr_batch  = explode("\n",$batchsearch);
					foreach($arr_batch as $key=>$value){
						if(trim($value)){
							$conn.="'".trim($value)."'".",";
						}
					}
					$conn = trim($conn,",");
					 $where.=" AND ( order_sn in({$conn}) or shipping_number in ({$conn}) or tradeid in ({$conn}) ) ";
				}
		       
		        $this->pageSize = 1000;

				
	        }
	        if($flagtype==2){
		        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
		        $objExcel = new PHPExcel();
		        $conn = "";
		        $arr_batch  = explode("\n",$batchsearch);
		        foreach($arr_batch as $key=>$value){
			        if(trim($value)){
				        $conn.="'".trim($value)."'".",";
			        }
		        }
		        $conn = trim($conn,",");
		        $where ="SELECT * FROM db_order_list where 1 AND ( order_sn in({$conn}) or shipping_number in ({$conn}) or tradeid in ({$conn}) ) ";
		        $result = $this->db->query($where)->result_array();

		        $objExcel->setActiveSheetIndex(0);
		        $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
		        $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(22);
		        $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(22);

		        $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(22);
		        $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
		        $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
		        $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		        $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(26);
		        $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
		        $objExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('L')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('M')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('N')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('O')->setWidth(10);
		        //设置标题
		        $objExcel->setActiveSheetIndex(0)->setCellValue('A1','订单时间');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('B1','店铺名称');

		        $objExcel->setActiveSheetIndex(0)->setCellValue('C1','收件人');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('D1','地址1');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('E1','地址2');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('F1','城市');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('G1','省份');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('H1','国家');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('I1','邮编');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('J1','电话1');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('K1','电话2');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('L1','称重重量');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('M1','运单号');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('N1','真实物流费');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('O1','预估物流费');

		        foreach($result as $k=>$v){
			        $sql = "SELECT group_concat(goods_sn) as goods_sn,group_concat(goods_number) as goods_number FROM db_order_sell WHERE order_id = '{$v['order_id']}' ";
			        $rs  = $this->db->query($sql)->row_array();
			        $arr_goods_sn = explode(",",$rs['goods_sn']);
			        $arr_goods_number = explode(",",$rs['goods_number']);
			        $str_sku = "";
			        foreach($arr_goods_sn as $kk=>$vv){
				        $str_sku .= $vv.",".$arr_goods_number[$kk].";";
			        }


			        $count = $k+2;
			        $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['ordertime']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['shopname']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['consignee']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['address']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['address2']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['city']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$v['province']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$v['country_cn']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('I'.$count,$v['zipcode']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('J'.$count,$v['tel']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('K'.$count,$v['mobile']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('L'.$count,$v['actionorderweight']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('M'.$count,$v['shipping_number']." ");
			        $objExcel->setActiveSheetIndex(0)->setCellValue('N'.$count,$v['shipping_realfee']." ");
			        $objExcel->setActiveSheetIndex(0)->setCellValue('O'.$count,$v['shipping_expectfee']." ");
		        }
		        $excel_name = date("YmdHis");
		        header("Content-type:application/vnd.ms-excel;charset=gb2312");
		        header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
		        header('Cache-Control: max-age=0');
		        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
		        $objWriter->save('php://output');
		        exit;


	        }

        }

		if($this->input->get_post('order_id'))
		{
			$order_id = $this->input->get_post('order_id');
			$where.=" AND order_id in($order_id)";
		}

        if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k amzorderid='" . $r . "'";
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 order_sn =   '" . $other . "'
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }
        if (intval($this->input->get_post('ordersearchID'))) {
            $ordersearchID = intval($this->input->get_post('ordersearchID'));
			if($ordersearchID)
			{
				//未分仓的不显示
				$where.=" AND shipping_status !=0";
			}
            $ordersearch = $this->m->getordersearch($ordersearchID);
			
            if ($ordersearch[0]["name"]) {
                if ($ordersearch[0]["sqlfilter"])
                    $where .= $ordersearch[0]["sqlfilter"];
                $this->tpl->assign("ordersearchname", $ordersearch[0]["name"]);
                //$this->tpl->assign("ordersearchID", $ordersearchID);
            }

        }
        if ($this->input->get('ty') == 1 || $this->input->get('ty') == '') $tys = 'ordertime';
        if ($this->input->get('ty') == 2) $tys = 'add_time';
        if ($this->input->get('ty') == 3) $tys = 'shipping_time';
        if ($this->input->get('ty') == 4) $tys = 'finshtime';
        $this->tpl->assign("ty", trim($this->input->get_post('ty')));
        $starttime = trim($this->input->get('starttime'));
        if ($starttime) {
            $times = $starttime . " 00:00:00";
            if ($this->input->get('ty') == 2 || $this->input->get('ty') == 3) $times = strtotime($times);
            $where .= " AND ($tys >= '" . $times . "')";
            $this->tpl->assign("starttime", $starttime);
        }

        $endtime = trim($this->input->get('endtime'));
        if ($endtime) {
            $times = $endtime . " 23:59:59";
            if ($this->input->get('ty') == 2 || $this->input->get('ty') == 3) $times = strtotime($times);
            $where .= " AND ($tys <= '" . $times . "')";
            $this->tpl->assign("endtime", $endtime);
        }
		if (intval($this->input->get_post('current')))    //今日订单
        {
			 $this->tpl->assign("current", 1);
		}
        if (intval($this->input->get_post('isow')))    //超重
        {

            $where .= " and  (is_overweight = 1) ";
        }
        if (intval($this->input->get_post('isno')))    //禁止发货
        {
            $where .= " and  (is_nodelivery = 1) ";
        }
        if (intval($this->input->get_post('que')))    //是否缺货
        {
            $que = intval($this->input->get_post('que'));
			if($que==1)
			{
				 //$where .= " and  (is_que = '" . $que . "') ";
				 //缺货
				 $where.=" AND (order_status = 2 or order_status=3) AND shipping_status = 5 and is_nodelivery=0";
				 $where .= " and order_id in(select distinct order_id from db_order_sell A left JOIN db_goods_stock B on A.goods_id=B.goods_id where B.stock<=0  and B.storage_id = 1 )";
			}else{
				//不缺货
				$where.=" AND (order_status = 2 or order_status=3) AND shipping_status = 5 and is_nodelivery=0";
				$where .= " and order_id in(select distinct order_id from db_order_sell A left JOIN db_goods_stock B on A.goods_id=B.goods_id where B.stock>0 and B.storage_id = 1 )";
			}

        }
		if(intval($this->input->get('isf')))	//可发货
		{
			/*	可发货条件
				1、已支付订单
				2、延迟2天以上
				3、有仓位
				4、有库存
			*/
			$where.=" AND (order_status in(2,3))";
			$where.=" AND is_nodelivery = 0";
			$where.=" AND ordertime < '".date("Y-m-d H:i:s",time()-86400*2)."'";
			$where.=" AND platformID !=5 and platformID !=6 and shopid !=303 and shopid !=174 and shopid !=147 and shopid !=17 and platformID !=21";
			$where .= " and order_id in(select distinct order_id from db_order_sell A left JOIN db_goods_stock B on A.goods_id=B.goods_id where B.stock>0 and B.positions like '%.%')";
		}
		//平台
		
		if (intval($this->input->get_post('platformID')))    //平台
        {
			/*
            $platformID = intval($this->input->get_post('platformID'));
			$this->tpl->assign("platformID", $platformID);
			if($platformID && intval($this->input->get_post('shopID'))=='')
			{
				$shopIDList = $this->m->getshopIDlist($platformID);
				if($shopIDList)
				{
					 $where .= " and  (shopid in ($shopIDList)) ";
				}
			}*/
			$platformID = intval($this->input->get_post('platformID'));
			$this->tpl->assign("platformID", $platformID);
			 $where .= " and platformID = $platformID";
        }
        if (intval($this->input->get_post('shopID'))) {
            $shopID = intval($this->input->get_post('shopID'));
            $where .= " and  (shopid =   '" . $shopID . "') ";
            $this->tpl->assign("shopID", $shopID);
        }
        if (intval($this->input->get_post('status'))) {
            $status = intval($this->input->get_post('status'));
            $where .= " and  (order_status =   '" . $status . "') ";
            $this->tpl->assign("status", $status);
        }else{
			$kw = trim($this->input->get_post('kw'));
			if($kw)
			{
				 $where.= "";
			}else{
				 $where.=" AND order_status !=6";
			}

			
		}
        if ($this->input->get_post('expresstype')) {
            $expresstype = $this->input->get_post('expresstype');
            $where .= " and  (shipping_name =   '" . $expresstype . "') ";
            $this->tpl->assign("expresstypeID", $expresstype);
        }
		

        if ($this->input->get_post('filtertype')) {
            $filtertype = trim($this->input->get_post('filtertype'));
            $kw = trim($this->input->get_post('kw'));
            if ($filtertype == 'productname') {
                $where .= " and order_id in(select distinct order_id from db_order_sell where goods_name like '" . $kw . "')";
            } elseif ($filtertype == 'productid') {
                $where .= " and order_id in(select distinct order_id from db_order_sell where goods_sn like '%" . $kw . "%')";
            } elseif ($filtertype == 'custome') {
                $where .= " and  (customerid like '%" . $kw . "%') ";
            } else {
                $where .= " and  ($filtertype =   '" . $kw . "') ";
            }
            $this->tpl->assign("filtertype", $filtertype);
            $this->tpl->assign("kw", $kw);
        }
        if ($this->input->get_post('filtertype') == "" && trim($this->input->get_post('kw'))) {
            $kw = trim($this->input->get_post('kw'));
            $where .= " and  (
					 order_sn like   '%" . $kw . "%'
					 or tradeid like '%" . $kw . "%'
					) ";
            $this->tpl->assign("kw", $kw);
        }

        if ($this->input->get_post('st')) {
            $st = $this->input->get_post('st');
            $where .= " and  (order_source =   '" . $st . "') ";
            $this->tpl->assign("st", $st);
        }
        if ($this->input->get_post('shippingStatus')) {
            $shippingStatus = $this->input->get_post('shippingStatus');
            //1好仓
            if($shippingStatus==1){
                $shipping_status = 5;
            }
            //2号仓
            if($shippingStatus==2){
                $shipping_status = 6;
            }
            //英国仓
            if($shippingStatus==3){
                $shipping_status = 1;
            }
            //德国仓
            if($shippingStatus==5){
                $shipping_status = 2;
            }
            //EZGO美国仓
            if($shippingStatus==6){
                $shipping_status = 3;
            }
            //万邑通美西仓
            if($shippingStatus==7){
                $shipping_status = 4;
            }
            //未分仓
            if($shippingStatus==9999){
                $shipping_status = 0;
            }
            $where .= " and  (shipping_status =   '" . $shipping_status . "') ";
            $this->tpl->assign("shippingStatus", $shippingStatus);
        }
		/*查询绑定的店铺订单**/
		if($_COOKIE["department"] ==1 || $_COOKIE["department"] ==2 || $_COOKIE["classid"] ==10)
		{
			if($_COOKIE["classid"] == 12 || $_COOKIE["classid"] ==13 || $_COOKIE["classid"] ==16)	//如果是工厂主管也是需要绑定的
			{
				$where.=$this->fun->getshopnameauth();
			}
		}else{
			
			$where.=$this->fun->getshopnameauth();
		}
		//print_r($this->input->get());
		if($this->input->get('byt'))
		{
			$byt = trim($this->input->get('byt'));
			if($byt == 'numday') //按延迟天数排
			{
				$orderbyst = trim($this->input->get('orderby'))?trim($this->input->get('orderby')):'ASC';
				$orderby = " order by ordertime $orderbyst ";
				if($orderbyst=='ASC')
				{
					$this->tpl->assign("orderbyst", 'DESC');
				}else{
					$this->tpl->assign("orderbyst", 'ASC');
				}
			}
		}else{
			// $orderby = ' order by order_status ASC ,add_time DESC';
			 $orderby = ' order by order_id DESC';
		}
        $wherefield =  "order_id,order_sn,actionorderweight,order_status,order_source,shipping_status,customerid,country_cn,country,email,shopname,shopoper,shopid,moneytype,tradeid,shipping_name,shipping_number,goods_amount,shipping_fee,goods_originask,
		add_time,ordertime,platform_message,remark,is_que,is_overweight,is_nodelivery";
        if(trim($this->input->get_post('outexcel'))==1){
            $wherefield.=",consignee,province,city,tel,mobile,address,address2,orderweight";
            $this->pageSize = 1000000;//最多1000条数据
        }
        $list = $this->fun->getalllist("db_order_list ", $where, $nowpage, $if_csv, $this->pageSize, $orderby, $wherefield);
		
		//导入excel
        if(trim($this->input->get_post('outexcel'))==1){
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            $objExcel = new PHPExcel();

            $objExcel->setActiveSheetIndex(0);
            $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
            $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(22);
            $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
            $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(26);
            $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
            $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
            $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
            $objExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('O')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('P')->setWidth(15);
	        $objExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);

            //设置标题
            $objExcel->setActiveSheetIndex(0)->setCellValue('A1','订单编号');
            $objExcel->setActiveSheetIndex(0)->setCellValue('B1','店铺');
            $objExcel->setActiveSheetIndex(0)->setCellValue('C1','商品sku');
            $objExcel->setActiveSheetIndex(0)->setCellValue('D1','货运方式');
            $objExcel->setActiveSheetIndex(0)->setCellValue('E1','交易单号');
            $objExcel->setActiveSheetIndex(0)->setCellValue('F1','订单重量');
            $objExcel->setActiveSheetIndex(0)->setCellValue('G1','订单金额');
            $objExcel->setActiveSheetIndex(0)->setCellValue('H1','运单号');


            $objExcel->setActiveSheetIndex(0)->setCellValue('I1','国家');
            $objExcel->setActiveSheetIndex(0)->setCellValue('J1','收件人');
            $objExcel->setActiveSheetIndex(0)->setCellValue('K1','省份');
            $objExcel->setActiveSheetIndex(0)->setCellValue('L1','城市');
            $objExcel->setActiveSheetIndex(0)->setCellValue('M1','地址1');
            $objExcel->setActiveSheetIndex(0)->setCellValue('N1','地址2');
            $objExcel->setActiveSheetIndex(0)->setCellValue('O1','电话');
            $objExcel->setActiveSheetIndex(0)->setCellValue('P1','手机');
	        $objExcel->setActiveSheetIndex(0)->setCellValue('Q1','称重重量');

            foreach($list['list'] as $k=>$v){
                $sql = "SELECT group_concat(goods_sn) as goods_sn,group_concat(goods_number) as goods_number FROM db_order_sell WHERE order_id = '{$v['order_id']}' ";
                $rs  = $this->db->query($sql)->row_array();
                $arr_goods_sn = explode(",",$rs['goods_sn']);
                $arr_goods_number = explode(",",$rs['goods_number']);
                $str_sku = "";
                foreach($arr_goods_sn as $kk=>$vv){
                    $str_sku .= $vv.",".$arr_goods_number[$kk].";";
                }


                $count = $k+2;
                $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['order_sn']." ");
                $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['shopname']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$str_sku." ");
                $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['shipping_name']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['tradeid']." ");
                $objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['orderweight']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$v['goods_amount']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$v['shipping_number']." ");
                $objExcel->setActiveSheetIndex(0)->setCellValue('I'.$count,$v['country_cn']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('J'.$count,$v['consignee']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('K'.$count,$v['province']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('L'.$count,$v['city']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('M'.$count,$v['address']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('N'.$count,$v['address2']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('O'.$count,$v['tel']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('P'.$count,$v['mobile']);
	            $objExcel->setActiveSheetIndex(0)->setCellValue('Q'.$count,$v['actionorderweight']);
            }
            $excel_name = date("YmdHis");
            header("Content-type:application/vnd.ms-excel;charset=gb2312");
            header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;
        }
       // echo $this->db->last_query();
        foreach ($list["list"] as $key => $rs) {

            switch ($rs["order_status"]) {
                case 1;
                    $list["list"][$key]["statustext"] = '新订单';
                    break;
                case 2:
                    $list["list"][$key]["statustext"] = '已支付';
                    break;
                case 3:
                    $list["list"][$key]["statustext"] = '配货中';
                    break;
                case 4:
                    $list["list"][$key]["statustext"] = '已发货';
                    break;
                case 5:
                    $list["list"][$key]["statustext"] = '已完成';
                    break;
                case 6:
                    $list["list"][$key]["statustext"] = '已作废';
                    break;
                case 7:
                    $list["list"][$key]["statustext"] = '待审查';
                    break;
            }
			$numday = (time() - strtotime($rs["ordertime"])) / 86400;
			if($numday<1)
			{
				$numday = 0;
			}else{
				$numday =intval($numday);
			}
            $list["list"][$key]["numday"] = $numday; //延迟天数
            $list["list"][$key]["goods_total"] = $rs["goods_amount"] + $rs["shipping_fee"]; //订单合计金额 = 商品金额+运费-平台-支付-商品成本
			
			if($rs["shopoper"]=="")
			{
				$shop = $this->fun->getdatabasesdetail("d_shop", " AND id='" . $rs["shopid"] . "'");    //负责人
				$list["list"][$key]["shopoper"] = $shop["updateoper"];
				$list["list"][$key]["platfromname"] = $shop["platfromname"];
			}
			$list["list"][$key]["add_time"] = date("Y-m-d H:i:s",$rs["add_time"]);
			
			
        }
		
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		if($platformID){
			$whereshop = " AND platfrom = ".$platformID."";
		}
		if($shopwhere)
		{
			$whereshop.=$shopwhere;
		}
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND del_flag= 0 $whereshop", 'id,name', ' order by name asc'));            //查所有店铺
        $this->tpl->assign("orderlist", $list["list"]);
		 $this->tpl->assign("today", date("Y-m-d"));
		 $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));//所有平台
        $this->tpl->assign("expresstype", $this->m->getorderexpress());//货运方式
        $this->tpl->assign("warehouses", $this->m->getWarehouses());//货运方式
        $this->tpl->assign("ordersearch", $this->m->getordersearch());//订单搜索脚本
        $this->tpl->assign("shops", $this->m->getWhereShops());//订单导入店铺 天猫 淘宝

		$t2 = microtime(true);
		$memory_get_usage = round(memory_get_usage()/1024,2);
		$vals='页面执行耗时 '.round($t2-$t1,3).'秒&nbsp;&nbsp;&nbsp;';
		$this->tpl->assign("showmemorygetusage", $vals);//
        $this->tpl->display("orderlist/orderlist.tpl");
    }

	/******订单错误日志****/
	public function orderlog()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;

        $where = " AND order_status =7";
		
		if($this->input->get_post('order_id'))
		{
			$order_id = $this->input->get_post('order_id');
			$where.=" AND order_id in($order_id)";
		}

        if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k amzorderid='" . $r . "'";
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 order_sn =   '" . $other . "'
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }
        if (intval($this->input->get_post('ordersearchID'))) {
            $ordersearchID = intval($this->input->get_post('ordersearchID'));
            $ordersearch = $this->m->getordersearch($ordersearchID);
            if ($ordersearch[0]["name"]) {
                if ($ordersearch[0]["sqlfilter"])
                    $where .= $ordersearch[0]["sqlfilter"];
                $this->tpl->assign("ordersearchname", $ordersearch[0]["name"]);
                //$this->tpl->assign("ordersearchID", $ordersearchID);
            }

        }
        if ($this->input->get('ty') == 1 || $this->input->get('ty') == '') $tys = 'ordertime';
        if ($this->input->get('ty') == 2) $tys = 'add_time';
        if ($this->input->get('ty') == 3) $tys = 'shipping_time';
        if ($this->input->get('ty') == 4) $tys = 'finshtime';
        $this->tpl->assign("ty", trim($this->input->get_post('ty')));
        $starttime = trim($this->input->get('starttime'));
        if ($starttime) {
            $times = $starttime . " 00:00:00";
            if ($this->input->get('ty') == 2 || $this->input->get('ty') == 3) $times = strtotime($times);
            $where .= " AND ($tys >= '" . $times . "')";
            $this->tpl->assign("starttime", $starttime);
        }

        $endtime = trim($this->input->get('endtime'));
        if ($endtime) {
            $times = $endtime . " 23:59:59";
            if ($this->input->get('ty') == 2 || $this->input->get('ty') == 3) $times = strtotime($times);
            $where .= " AND ($tys <= '" . $times . "')";
            $this->tpl->assign("endtime", $endtime);
        }

        if (intval($this->input->get_post('isow')))    //超重
        {

            $where .= " and  (is_overweight = 1) ";
        }
        if (intval($this->input->get_post('isno')))    //禁止发货
        {
            $where .= " and  (is_nodelivery = 1) ";
        }
        if (intval($this->input->get_post('que')))    //是否缺货
        {
            $que = intval($this->input->get_post('que'));
            $where .= " and  (is_que = '" . $que . "') ";
        }

        if (intval($this->input->get_post('shopID'))) {
            $shopID = intval($this->input->get_post('shopID'));
            $where .= " and  (shopid =   '" . $shopID . "') ";
            $this->tpl->assign("shopID", $shopID);
        }
        if (intval($this->input->get_post('status'))) {
            $status = intval($this->input->get_post('status'));
            $where .= " and  (order_status =   '" . $status . "') ";
            $this->tpl->assign("status", $status);
        }
        if (intval($this->input->get_post('expresstype'))) {
            $expresstype = intval($this->input->get_post('expresstype'));
            $where .= " and  (shipping_id =   '" . $expresstype . "') ";
            $this->tpl->assign("expresstypeID", $expresstype);
        }

		if (intval($this->input->get_post('platformID')))    //平台
        {
			$platformID = intval($this->input->get_post('platformID'));
			$this->tpl->assign("platformID", $platformID);
			 $where .= " and platformID = $platformID";
        }

        if ($this->input->get_post('filtertype')) {
            $filtertype = trim($this->input->get_post('filtertype'));
            $kw = trim($this->input->get_post('kw'));
            if ($filtertype == 'productname') {
                $where .= " and order_id in(select distinct order_id from db_order_sell where goods_name like '" . $kw . "')";
            } elseif ($filtertype == 'productid') {
                $where .= " and order_id in(select distinct order_id from db_order_sell where goods_sn like '" . $kw . "')";
            } elseif ($filtertype == 'custome') {
                $where .= " and  (customerid like '%" . $kw . "%') ";
            } else {
                $where .= " and  ($filtertype =   '" . $kw . "') ";
            }
            $this->tpl->assign("filtertype", $filtertype);
            $this->tpl->assign("kw", $kw);
        }
        if ($this->input->get_post('filtertype') == "" && trim($this->input->get_post('kw'))) {
            $kw = trim($this->input->get_post('kw'));
            $where .= " and  (
					 order_sn =   '" . $kw . "'
					 or tradeid= '" . $kw . "'
					) ";
            $this->tpl->assign("kw", $kw);
        }

        if ($this->input->get_post('st')) {
            $st = $this->input->get_post('st');
            $where .= " and  (order_source =   '" . $st . "') ";
            $this->tpl->assign("st", $st);
        }

		if($_COOKIE["classid"]==14 || $_COOKIE["classid"] == 12 || $_COOKIE["classid"] ==13 || $_COOKIE["classid"] ==16)
		{
			$where.=$this->fun->getshopnameauth();
		}
		

        $orderby = ' order by order_id DESC';
        $list = $this->fun->getalllist("db_order_list A $dbname", $where, $nowpage, $if_csv, $this->pageSize, $orderby, "A.*");
        foreach ($list["list"] as $key => $rs) {

            switch ($rs["order_status"]) {
                case 1;
                    $list["list"][$key]["statustext"] = '新订单';
                    break;
                case 2:
                    $list["list"][$key]["statustext"] = '已支付';
                    break;
                case 3:
                    $list["list"][$key]["statustext"] = '配货中';
                    break;
                case 4:
                    $list["list"][$key]["statustext"] = '已发货';
                    break;
                case 5:
                    $list["list"][$key]["statustext"] = '已完成';
                    break;
                case 6:
                    $list["list"][$key]["statustext"] = '已作废';
                    break;
                case 7:
                    $list["list"][$key]["statustext"] = '待审查';
                    break;
            }
            $list["list"][$key]["add_time"]=date("Y-m-d H:i",$rs['add_time']);
            $list["list"][$key]["numday"] = intval((time() - strtotime($rs["ordertime"])) / 86400); //延迟天数
            $list["list"][$key]["goods_total"] = $rs["goods_amount"] + $rs["shipping_fee"]; //订单合计金额 = 商品金额+运费-平台-支付

            $shop = $this->fun->getdatabasesdetail("d_shop", " AND name='" . $rs["shopname"] . "'");    //负责人
            $list["list"][$key]["responsible"] = $shop["updateoper"];
            $list["list"][$key]["platfromname"] = $shop["platfromname"];
        }
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND del_flag= 0", 'id,name', ' order by name asc'));            //查所有店铺
        $this->tpl->assign("orderlist", $list["list"]);
		 $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));//所有平台
        $this->tpl->assign("expresstype", $this->m->getorderexpress());//货运方式
        $this->tpl->assign("ordersearch", $this->m->getordersearch());//订单搜索脚本
        $this->tpl->display("orderlist/orderlog.tpl");
	}
	
	/***********添加新的订单***************/
	public function addorder()
	{
		$sn = $this->input->get('copyid');
		$replay = $this->input->get('replay');	//重发
		if($sn){
		 $detail = $this->fun->getdatabasesdetail("db_order_list", " AND order_sn='" . $sn . "'");
		 $detail['country'] = strtolower($detail["country"]);
		 if($replay==1)
		 {
			$ornum = $this->fun->getdatabaseslist("db_order_list", " AND tradeid like'%".$detail['tradeid']."%'");
			$detail["tradeid"] = $detail["tradeid"]."-1";
		 }
		 $this->tpl->assign("detail", $detail);
		 //获取原来订单的SELL
		$sell = $this->db->get_where("db_order_sell", " order_id ='".$detail['order_id']."'")->result_array();
		$this->tpl->assign("goodslist", $sell);
		}
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND del_flag= 0", 'id,name', ' order by name asc'));            //查所有店铺
		$country = $this->fun->getdatabaseslist('d_country', "", 'countrynamecn');
		foreach($country as $key=>$rs)
		{
			$st["countrynamecn"] = strtolower($rs["countrynamecn"]);
			$newcountry[] = $st;
		}
		
		if($replay==1)
		{
			$this->tpl->assign("st", '已收到重发');
			$this->tpl->assign("replay", $replay);
			
		}
		$this->tpl->assign("d_country", $newcountry);            //查所有国家
		$this->tpl->assign("moneyratelist", $this->fun->getmoneyrate());	//货币列表
		$this->tpl->display("orderlist/addorder.tpl");
	}
    /*****订单编辑************/
    public function editorder()
    {
        $allcostprice = $allsale = $totalgoods = 0;
        $order_id = intval($this->input->get('order_id'));
        $sn = trim($this->input->get('sn'));
        if ($sn) {
            $detail = $this->fun->getdatabasesdetail("db_order_list", " AND order_sn='" . $sn . "'");
            $order_id = $detail["order_id"];
        } else {
            $detail = $this->fun->getdatabasesdetail("db_order_list", " AND order_id='" . $order_id . "'");
        }
		if (!$detail) {
            die('参数传递错误或你无权查看该订单！<input type="button" name="back" value="返回上一页" onclick="javascript:history.back(-1);"/>');
        }
	    if(!$detail['shopoper']){
			    $sql_shop = "SELECT * FROM d_shop WHERE id = '{$detail['shopid']}' ";
			    $rs_shop  = $this->db->query($sql_shop)->row_array();
		         $detail['shopoper']  = $rs_shop['updateoper'];//店铺负责人
		         //$this->db->update("db_order_list",array("shopoper"=>$rs_shop['updateoper'])," order_id='".$detail['order_id']."'");
	    }

		
		if($detail['moneyrate'])
		{
			$detail["platform_originfee"] = round($detail["platform_fee"] / $detail['moneyrate'], 2);
			$detail["pay_originfee"] = round($detail["pay_fee"] / $detail['moneyrate'], 2);
		}else{
			$moneyrate = $this->fun->getdatabasesdetail("d_moneyrate", " AND name='" . $detail["moneytype"] . "'");
			if ($moneyrate) {
				$detail["moneyrate"] = $moneyrate["rate"];
				$detail["platform_originfee"] = round($detail["platform_fee"] / $moneyrate["rate"], 2);
				$detail["pay_originfee"] = round($detail["pay_fee"] / $moneyrate["rate"], 2);
			}
		}
		
        
		if($detail['shipping_realfee']==0)
		{
			$detail['shipping_realfee'] = "";
		}
        
        switch ($detail["order_status"]) {
            case 1;
                $detail["statustext"] = '新订单';
                break;
            case 2:
                $detail["statustext"] = '已支付';
                break;
            case 3:
                $detail["statustext"] = '配货中';
                break;
            case 4:
                $detail["statustext"] = '已发货';
                break;
            case 5:
                $detail["statustext"] = '已完成';
                break;
            case 6:
                $detail["statustext"] = '已作废';
                break;
            case 7:
                $detail["statustext"] = '待审查';
                break;
        }

        /*商品信息*/
        $goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_goods B ON A.goods_sn=B.goods_sku", " AND order_id='" . $order_id . "'");
		$isstopsales = 0;
        if (count($goodslist) > 0) {
			$allgoods_number = 0;
            foreach ($goodslist as $key => $rs) {
                $acostprice = 0;
                $goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $rs["goods_id"])->result_array();
                $thumb_url = $goods_images[0]["thumb_url"];
                if ($thumb_url) {
                    $goodslist[$key]["thumb_url"] = $thumb_url;
                    $goodslist[$key]["local_url"] = $goods_images[0]["local_url"];
                } else {
                    $goodslist[$key]["thumb_url"] = "/fuman/images/s-l500.jpg";
                }

				/********如果是鞋子并且是高菲菲,并且主SKU等于子SKU***************/
				if($this->config->item('isopenshoescustom') == 1){
					if($rs["g_checkman"] =='高菲菲' && strpos($rs["goods_name"],'鞋') !== false && $rs["goods_parent_sku"] == $rs["goods_sku"])
					{
						$goodslist[$key]["isshow_shoes_custom"] = 1;
					}else{
						$goodslist[$key]["isshow_shoes_custom"] = 0;
					}

					//默认值
					$sellassist = $this->fun->getdatabasesdetail('db_order_assist'," AND order_id= '".$order_id."' AND sellID = '".$rs["rec_id"]."' AND types= 1");
					if($sellassist)
					{
						 $goodslist[$key]["sellassist"] = $sellassist;
					}

					
				}

				if($rs["product_link"])
				{
					if($detail['saleschannel'] =='Aliexpress')
					{
						if($rs['productId']){
							$itemUrl = "http://www.aliexpress.com/item/-/".$rs['productId'].".html";
						}
					}
					if($detail['saleschannel'] =='eBay')
					{
						$itemUrl = "http://www.ebay.com/itm/".$rs['product_link'];
					}
					if($detail['saleschannel'] =='wish')
					{
						$itemUrl = $rs['product_link'];
					}
					
					$goodslist[$key]["itemUrl"] = $itemUrl;
				}
				
				$costprice = $rs["costprice"];
                $acostprice = $costprice * $rs["goods_number"];
                $allcostprice = $allcostprice + $acostprice;
                $totalgoods = $totalgoods + $rs["goods_number"];
				$allgoods_number = $allgoods_number+$rs['goods_number'];

              //  if ($rs["goods_amount"] > 0) $goodslist[$key]["maolilv"] = round((($rs["goods_amount"] - $acostprice) / $rs["goods_amount"]), 2) * 100;    //单个商品的毛利率

                //获取库存信息
                //$stock = $this->db->get_where("db_goods_stock", array("goods_id" => $rs["goods_id"]))->result_array();

				$stock = $this->fun->getdatabaseslist("db_goods_stock A LEFT JOIN db_storage B on A.storage_id=B.id"," AND B.is_show=1 and A.goods_id='".$rs["goods_id"]."'","A.*");

                if ($stock) {
                    $goodslist[$key]["stock"] = $stock;
                } else {
                    $goodslist[$key]["stock"] = 0;
                }
				
				$arrgoodsID[] = $rs["goods_id"];
				
				//商品状态为停售
				if($rs["g_sale_status"]==4)
				{
					$isstopsales = 1;
				}

            }
			if((count($arrgoodsID) == count(array_filter($arrgoodsID))) && $detail["order_status"]==7)	//如果值相等,并且是待审核状态，则显示导入订单流程按钮
			{
				/***********暂时判断备注中是否包含停售商品内容，之后判断购买的SKU是否都是正常销售的商品，都是正常商品就显示生成正式订单按钮***********/
				if($isstopsales==0){
					$this->tpl->assign("isyesstatushaltgoods", 0);
				}else{
					$this->tpl->assign("isyesstatushaltgoods", 1);
				}

				
				$this->tpl->assign("isyesstatus", 1);
			}else{
				$this->tpl->assign("isyesstatus", 0);
			}
			
        }
		
		if($detail["shipping_realfee"]>0)
				$shippingfee = $detail["shipping_realfee"];
			else
				$shippingfee = $detail["shipping_expectfee"];

        $detail["allsale"] = $detail["goods_amount"] + $detail["shipping_fee"];
             $last_money=0;
             $sql="select sum(refund_money) as lastmoney from db_paypal_refund where order_id='{$order_id}';";
             $last=$this->db->get_one($sql);
             if ($last) {
                 $last_money=round($last['lastmoney'],2);
             }
			 
		$detail["alloriginsale"] = $detail["goods_originask"] + $detail["shipping_originask"]-$last_money;	//原始总收入金额
        $detail["allcostprice"] = $allcostprice;    //商品成本合计
        $detail["totalgoods"] = $totalgoods;    //商品数量合计
		$detail["allgoods_number"] = $allgoods_number;    //商品数量合计
	
        $detail["allmoney"] = $detail["goods_amount"] + $detail["shipping_fee"] - $allcostprice - $shippingfee - $detail["platform_fee"] - $detail["pay_fee"];
		$detail["allmoney"] = round($detail["allmoney"],2);
		//$saleschannel = strtolower(trim($detail["saleschannel"]));
		$platformID  = $detail["platformID"];
		if($platformID ==1 || $platformID ==14 || $platformID == 10 || $platformID ==23)
		{
			$detail["paypalback"] = 1; 
		}else{
			$detail["paypalback"] = 0; 
		}
		
        $orderlog = $this->db->order_by("id", 'DESC')->limit($this->config->item('configlognum'))->get_where('db_goods_log', 'types = 3 AND goods_id=' . $order_id)->result_array();    //订单日志
        $this->tpl->assign("orderexpress", $this->m->getorderexpress());    //查询所有快递方式
        $this->tpl->assign('platformID',$detail['platformID']);

        $this->tpl->assign("detail", $detail);
		$this->tpl->assign("moneyratelist", $this->fun->getmoneyrate());	//货币列表
        $this->tpl->assign("historyorder", $this->m->historyorder($order_id));//历史订单信息
        $this->tpl->assign("orderlog", $orderlog);
        $this->tpl->assign("goodslist", $goodslist);
	
        $this->tpl->display("orderlist/editorder.tpl");

    }

    function saveorder()
    {
		

		if(intval($this->input->post('orderId'))>0)
		{
			$orderID = $this->m->saveorderData();
		}else{
			
			$orderID = $this->m->insertorderData();
		}
        header("location:/orderlist/editorder?order_id=$orderID");
    }

    /***********订单合并*********/
    function mergeorder()
    {
        /****************************************
         *** 同店铺同一个客户同一个地址即为可以合并
         * select `consignee`,count(*) as count from db_order_list group by `consignee` having count>1
         ********************************/
		 if($_COOKIE["classid"]==14 || $_COOKIE["classid"] == 12 || $_COOKIE["classid"] ==13 || $_COOKIE["classid"] ==16)	//工厂主管
		{
			 $this->tpl->display("orderlist/mergeorder.tpl");
			 die;
		}
		if($_COOKIE["userid"] == 365 || $_COOKIE["userid"]==133 || $_COOKIE["userid"]==360 || $_COOKIE["userid"]==295)
		{
			$where = " AND (country !='china' and country !='japan' and country !='Japan')";
		}else{
			$where="";
		}
        $sql = "SELECT order_sn, shopid, `consignee`,address ,tel, zipcode,COUNT( * ) AS count FROM db_order_list where (order_status = 1 or order_status =2 or order_status =7) AND order_source ='正常订单'  $where ANd consignee !='' GROUP BY  `consignee` HAVING count >1";
        $query = $this->db->query($sql);
        $dates = $query->result_array();
        foreach ($dates as $key => $rs) {
            $sql = "SELECT * FROM `db_order_list` WHERE `consignee` LIKE '" . addslashes($rs["consignee"]) . "' AND address ='".addslashes($rs['address'])."' AND zipcode='".$rs['zipcode']."' AND tel='".$rs['tel']."' AND shopid='" . $rs["shopid"] . "' AND (order_status = 1 or order_status =2 or order_status =7) AND shipping_id !=22 AND order_source ='正常订单' $where ";
            $query = $this->db->query($sql);
            $linkdates = $query->result_array();
            if (count($linkdates) > 1) {
                $newdates[$key] = $linkdates;
            }
        }

        if (count($newdates) > 0) {
            $newdates = array_merge($newdates);    //重新排序
            foreach ($newdates as $key => $res) {
                foreach ($res as $s => $rs) {
                    if ($key % 2 == 1) {
                        $newdates[$key][$s][color] = "#FFFFFF";
                    } else {
                        $newdates[$key][$s][color] = "#FFF9c4";
                    }
                }

            }
        }

		
        $this->tpl->assign("newdates", $newdates);
		$this->tpl->assign("usrid", $_COOKIE['userid']);
        $this->tpl->display("orderlist/mergeorder.tpl");

    }


    function ajaxbutton()
    {
        $op = $this->input->get_post('op');
        /*****************
         ** 查询亚马逊订单商品
         ** $id int
         *************/
        if ($op == 'showamazonsell') {
            echo json_encode($this->db->get_where("db_amzordertmpsell", array("ordertmpid" => intval($this->input->post("id"))))->result_array());
            die;
        }
        /*****************
         ** 查询订单商品
         ** $id int
         *************/
        if ($op == 'showOrderlistSell') {
            $res = $this->m->getOrderlistSell(intval($this->input->post("id")));
            echo json_encode($res);
            die;
        }
        /*****************
         ** 更新订单状态
         ** $id int
         ** $action string 修改改变的状态字段
         ** type 0,1
         *************/
        if ($op == 'changstatus') {
            $action = $this->input->post('action');
            $order_id = $this->input->post('order_id');
			if($this->input->post('type')==3)
			{
				//标配货中，必须是已支付状态
				  $this->db->update("db_order_list", array("$action" => $this->input->post('type')), " order_status = 2 and order_id=" . $this->input->post('order_id'));
			}else{
				  $this->db->update("db_order_list", array("$action" => $this->input->post('type')), "order_id=" . $this->input->post('order_id'));
			}
          
            if ($action == "is_nodelivery" && $this->input->post('type') == 1) {
                $ststustext = "禁止发货";
            }
            if ($action == "is_nodelivery" && $this->input->post('type') == 0) {
                $ststustext = "取消禁止发货";
            }
            if ($action == "order_status" && $this->input->post('type') == 6) {
                $ststustext = "作废";
                //判断商品是否为海外仓
                $sql = "SELECT * FROM db_order_list WHERE shipping_status in (1,2,3,4) AND order_id = '".$order_id."'";
                $rs  = $this->db->query($sql)->row_array();
                if($rs){
                    $rval = "修改状态为：$ststustext<br>";
                    $this->fun->goods_update_log($order_id, $rval, 3);    //日志

                    //这里需要传递order_sn过去
                    echo json_encode($rs['order_sn']);
                    //echo json_encode(204);
                    //echo json_encode($order_id."-该订单为海外仓订单，是否撤销海海外仓订单?");
                    exit;
                }
            }
            if ($action == "order_status" && $this->input->post('type') == 1) {
                $ststustext = "取消作废,当前订单状态自动修改为新订单";
            }
            if ($action == "order_status" && $this->input->post('type') == 2) {
                $ststustext = "收款,当前订单状态自动修改为已支付";
            }

			if ($action == "is_backpay" && $this->input->post('type') == 1) {
                 $ststustext = "Paypal退款,当前订单申请退款！";
				 $this->db->update("db_order_list", array("is_nodelivery" => 1), "order_id=" . $this->input->post('order_id'));
            }
			if ($action == "is_backpay" && $this->input->post('type') == 0) {
                 $ststustext = "取消申请Paypal退款";
				 $this->db->update("db_order_list", array("is_nodelivery" =>0), "order_id=" . $this->input->post('order_id'));
            }

            $rval .= "修改状态为：$ststustext<br>";
            $this->fun->goods_update_log($order_id, $rval, 3);    //日志
            echo json_encode(200);
            die;
        }
		
		  /*****************
         ** 保存paypal退款
         *************/
		if($op =='savepayrefund')
		{
			$order_id  =intval($this->input->post('order_id'));
			$refund_money = $this->input->post('refund_money');
			$refund_reason = $this->input->post('refund_reason');
			$otherpaypal= $this->input->post('otherpaypal');
            $ourpaypal = $this->input->post('ourpaypal');

			$rsdb = $this->fun->getdatabasesdetail("db_order_list", " AND order_id = '".$order_id."'");
			$post="";
			$post['order_sn'] = $rsdb['order_sn'];
			$post['refund_time'] = time();
			$post['refund_money'] = $refund_money;
			$post['refund_reason'] = $refund_reason;
			$post['refund_status'] = 1;
			$post['shipping_name'] = $rsdb['shipping_name'];
			$post['shipping_number'] = $rsdb['shipping_number'];
			$post['payid'] = $rsdb['payid'];
			$post['shop_id'] = $rsdb['shopid'];
			$post['goods_originask'] = $rsdb['goods_originask']+$rsdb['shipping_originask'];
			$post['goods_amount'] = $rsdb['goods_amount']+$rsdb['shipping_fee'];
			$post['moneytype'] = $rsdb['moneytype'];
			$post['ordertime'] = $rsdb['ordertime'];
			$post['shopoper'] = $_COOKIE["username"];
			$post['platfromname'] = $rsdb['saleschannel'];
			$post['shopname'] = $rsdb['shopname'];
			$post['order_id'] = $rsdb['order_id'];
            $post['otherpaypal']='对方paypal:'.$otherpaypal;
            if(!empty($ourpaypal)) $post['otherpaypal'] .="<br/>己方paypal:".$ourpaypal;
             $orderup ='';
             $last_money=0;
             $sql="select sum(refund_money) as lastmoney from db_paypal_refund where order_id='{$order_id}';";
			 $last = $this->db->get_one($sql);
             if($last){
                 $last_money=$last['lastmoney'];
             }
			
			
			$this->db->insert('db_paypal_refund',$post);

			 $lastmoney = round(($refund_money + $last_money),2);
			 $goodsmoney = round(($rsdb['goods_originask']+$rsdb['shipping_originask']),2);
			 if($lastmoney == $goodsmoney)
			 {
				$order_source = '全额退款';
				$orderup['order_status'] = 6;
				$orderup['is_nodelivery'] = 1;
				
			 }else{
				$order_source = '部分退款';
			 }
			$orderup['is_backpay'] = 1;
			$orderup['order_source'] = $order_source;

			 $ststustext = "Paypal退款,当前订单申请退款！<font color=blue><a href=\"/paypal/ajaxbutton?op=search&kw=$rsdb[order_sn]&status=3\">点击查看</font>";
			 $this->db->update("db_order_list", $orderup, "order_id=" . $rsdb['order_id']);
			 $rval= "修改状态为：$ststustext<br>";
			 $this->fun->goods_update_log($order_id, $rval, 3);    //日志
		}

		  /*****************
         ** 订单列表批量发货
         *************/
		if($op =='batchExpress')
		{
			 $this->tpl->display("orderlist/batchExpress.tpl",0,0,1);
		}
		
		/**批量修改内容**/
		if($op=='Bulkchanges')
		{
			$str = $this->input->get_post('str');
			if($str){
				$str = substr($str,0,-1);
				$newstr = explode(",",$str);
				$str = implode("\n",$newstr);
				$this->tpl->assign("orderlist", $str);
				$this->tpl->assign("countorder", count($newstr));
			}
			if($this->input->get('err')==1)
			{
				$this->tpl->assign("isok", "批量更新操作完成");
			}
			 $this->tpl->assign("expresstype", $this->m->getorderexpress());//货运方式
			 $this->tpl->assign("ordersearch", $this->m->getordersearch());//订单搜索脚本
			 $this->tpl->display("orderlist/Bulkchanges.tpl",0,0,1);
		}
		 /*****************
         ** 通过搜索脚本获取订单列表
         *************/
		if($op=='getordersearch')
		{
			 if (intval($this->input->get_post('ordersearchID'))) {
				$ordersearchID = intval($this->input->get_post('ordersearchID'));
				$ordersearch = $this->m->getordersearch($ordersearchID);
				if ($ordersearch[0]["name"]) {
					if ($ordersearch[0]["sqlfilter"])
						$where= $ordersearch[0]["sqlfilter"];
					
					$orderlist  = $this->fun->getdatabaseslist("db_order_list",$where);
					$order="";
					$num = 0;
					if(count($orderlist)>0)
					{
						foreach($orderlist as  $orderstr)
						{
							
							$order[] = $orderstr["order_sn"];
							$num=1;
						}
					}
					if($num==1)
					{
						$str = implode("\n",$order);
						echo $str;
						die;
					}else{
						echo " ";
						die;
					}
				}

			  }
		}
		if($op == 'saveBulkchanges')
		{
			if($this->m->saveBulkchanges())
			{
				header("location:/orderlist/ajaxbutton?op=Bulkchanges&err=1");
			}
		}
		/**批量修改内容结束**/

		if($op =='ActionbatchExpress')
		{
			$t1 = microtime(true);
			$orderid = trim($this->input->post('orderid'));	//订单ID
			$expressid = trim($this->input->post('expressid'));	//交运号
			$orderweight = trim($this->input->post('orderweight'));
			//未禁止发货以及配货中状态
			if($orderweight>30000)
			{
			  echo json_encode(array("code"=>201,"txt"=>"确认是否出错！重量必须小于30KG"));
			  die;
			}
				
			$rsdb = $this->fun->getdatabasesdetail("db_order_list", " AND shipping_number = '".$expressid."'","shipping_id,is_nodelivery,order_status,order_sn,shipping_number,country,province,country_cn,shipping_name,order_id,tradeid,shopname,consignee");
			if($rsdb['shipping_id'] == 10 || $rsdb['shipping_id'] == 11 || $rsdb['shipping_id'] == 22)
			{
				if($orderweight>1999)
				{
				  echo json_encode(array("code"=>201,"txt"=>"{$expressid} 超重!必须小于1999"));
				  die;
				}
			}
			
			
			if($rsdb['shipping_id'] == 23)	//UPS小于等于1000 或者小于3000
			{
				if($orderweight>=1000)
				{
				 
				}else{
					 echo json_encode(array("code"=>201,"txt"=>"{$expressid} 超重!UPS必须大于1000"));
					 die;
				}
			}
			if($rsdb['shipping_id'] == 46)	//佳成小于2000
			{
				if($orderweight<2000)
				{
				 
				}else{
					 echo json_encode(array("code"=>201,"txt"=>"{$expressid} 超重!佳成必须小于2000"));
					 die;
				}
			}
			
			if(!$rsdb)
			{
				 echo json_encode(array("code"=>201,"txt"=>"{$expressid} 运单号不存在!"));
				 die;
			}
			
			if($rsdb["is_nodelivery"]==1)
			{
				//禁止发货
				 echo json_encode(array("code"=>201,"txt"=>"{$orderid} 禁止发货!"));
				 die;
			}
			if($rsdb["order_status"] !=3)
			{
				//订单状态不是配货中
				switch ($rsdb["order_status"]) {
					case 1;
						$statustext = '新订单';
						break;
					case 2:
						$statustext = '已支付';
						break;
					case 3:
						$statustext = '配货中';
						break;
					case 4:
						$statustext = '已发货';
						break;
					case 5:
						$statustext = '已完成';
						break;
					case 6:
						$statustext = '已作废';
						break;
					case 7:
						$statustext = '待审查';
						break;
				 }
				 echo json_encode(array("code"=>201,"txt"=>"{$orderid} 订单状态是：{$statustext}"));
				 die;
			}
			if($_COOKIE["username"]=="")
			{
				 echo json_encode(array("code"=>201,"txt"=>"帐号被下线！请重新登录页面！再次打开扫单发货"));
				 die;
			}

			if($rsdb["is_nodelivery"]==0 && $rsdb["order_status"] ==3)
			{
				if($orderid != $expressid)
				{
					//说明订单号和运单号不是一样的。
					if($rsdb["order_sn"] == $orderid && $rsdb["shipping_number"] ==$expressid)
					{
					
					}else{
						 echo json_encode(array("code"=>201,"txt"=>"{$orderid} 交运号和订单号不一致!"));
						 die;
					}
				}

				if($rsdb["shipping_number"] != $expressid)
				{
					  echo json_encode(array("code"=>201,"txt"=>"{$orderid} 交运号不对应!"));
					  die;
				}
				
				//更新订单重量，自动标发货中
				$orderweightst = $orderweight;
				
				$postd="";
				$postd["actionorderweight"] = $orderweightst;
				$postd["order_status"] = 4;
				
				if($rsdb["country"]=='china' || $rsdb["province"]=='北海道' || $rsdb["province"]=='沖縄県')	//如果是中国的快递，使用省份重新计算预估运费
				{
					$country_cn= $rsdb['province'];
				}else{
					$country_cn= $rsdb["country_cn"];
				}
				$freigth = $this->fun->get_Estimate_freight($orderweightst,$country_cn,0,$rsdb["shipping_name"]);//重新计算预估运费
				if(is_numeric($freigth))
				{
					$postd["shipping_expectfee"] = $freigth;
				}
				$postd["shipping_time"] = time();//真实发货时间
				$this->db->trans_begin();	//事务开始
				
				try {
					$this->db->update("db_order_list",$postd," shipping_number = '".$expressid."' AND order_sn='".$rsdb["order_sn"]."'");
					//预留遇到个SKU的商品，需要计算一个SKU的重量
					 $skulistst = $this->fun->getdatabasesdetail("db_order_sell"," AND order_id=".$rsdb["order_id"]," GROUP_CONCAT(goods_sn) as sku,SUM(goods_number) skunum");
					 $skulist = ",".$skulistst['sku'].",";
					// $ordersellnums = $this->fun->getdatabasesdetail("db_order_sell"," AND order_id=".$rsdb["order_id"]," SUM(goods_number) skunum");
					//存出货记录
					$postdata="";
					$postdata["batch_order_sn"] = $rsdb["order_sn"];
					$postdata["batch_shipping_number"] = $expressid;
					$postdata["batch_shipping_name"] = $rsdb["shipping_name"];
					$postdata["batch_orderweight"] = $orderweightst;
					$postdata["oper"] = $_COOKIE["username"]?$_COOKIE["username"]:'郑超';
					$postdata["opertime"] = date("Y-m-d H:i:s");
					$postdata["yz"] = 0;
					$postdata["skuNum"] = $skulistst['skunum'];
					$postdata["skulist"] = $skulist;
					$this->db->insert("db_order_batchexpress",$postdata);
					 $rval .= "修改状态为：已发货 称重->{$orderweightst} 运单号->{$expressid}<br>";
					 $this->fun->goods_update_log($rsdb["order_id"], $rval, 3);    //日志
						
					 //自动减少库存
					 //查询所有的商品信息
					 $ordersell = $this->db->get_where("db_order_sell","order_id=".$rsdb["order_id"])->result_array();
					 if(count($ordersell)>0)
					 {
						foreach($ordersell as $key=>$resgoods)	//循环读取订单的销售列表
						{
							$storage  =1;
							$this->fun->inventory($rsdb["order_id"],$resgoods["goods_id"],$storage,$resgoods["goods_number"],0);
							 /***************************
							 ** 自动修正商品的重量信息
							 ** 扫单出货读取最近十笔单个SKU的订单，取平均值
							 *********************************/
							//$this->fun->getgoodsweigth($resgoods);
							 /***************************
							 ** 新系统扫单入库时，需要更新马帮的商品库存
							 ** changmabangstock($goods_id,$num,$order)
							 *********************************/
						}
					 }
					$this->db->trans_commit();
				 }catch(Exception $e){
					 $this->db->trans_rollback();
				 }

				$t2 = microtime(true);
				$memory_get_usage = round(memory_get_usage()/1024,2);
				$valst='执行耗时 '.round($t2-$t1,3).'秒&nbsp;&nbsp;内存 '.$memory_get_usage;
				echo json_encode(array("code"=>200,"txt"=>"订单号：{$rsdb[order_sn]} <br> 交易号：{$rsdb[tradeid]} <br> 店铺：{$rsdb[shopname]} <br> 买家：{$rsdb[consignee]} <br> 物流公司：<font color=red>{$rsdb[shipping_name]}</font> <br> 运单号：{$rsdb[shipping_number]} <br> 称重重量：{$orderweight} ","memo"=>"订单号：{$rsdb[order_sn]}  运单号：{$rsdb[shipping_number]} 重量：{$orderweight}  {$valst} \r\n "));
				
			}else{
				echo json_encode(array("code"=>201,"txt"=>"{$orderid} 订单异常!"));
				 die;
			}


		}
        
        /*****************
         ** 更新订单状态 Pro
         ** $id int
         ** $action string 修改改变的状态字段
         ** type 0,1
         *************/
        if ($op == 'changstatusPro') {
            $action = $this->input->post('action');
            $order_id = trim($this->input->post('order_id'));
            $type = $this->input->post('type');
            if ($order_id) {
                //	$order_id = substr($order_id,0,-1);
                $order_id = explode(",", $order_id);
                $order_id = array_filter($order_id);
                $numorder = count($order_id);


                $order_id = implode("','", $order_id);
            } else {
                $dates["code"] = 201;
                $dates["txt"] = "订单ID为空！";
                echo json_encode($dates);
                die;
            }

			 if ($numorder == 1) {
				$reslist = $this->db->get_where("db_order_list", " order_sn  = '" . $order_id . "'")->result_array();
			} else {
				$reslist = $this->db->get_where("db_order_list", "  order_sn in ('" . $order_id . "')")->result_array();
			}

            if ($type == 2)    //标收款,所选的订单必须全是新订单状态
            {
                //判断必须都是新订单状态
                foreach ($reslist as $key => $rs) {
                    if ($rs["order_status"] == 1) {
						$result_orderID[] = $rs["order_id"];	//存返回的订单ID号
                        $this->db->update("db_order_list", array("order_status" => 2), "order_id=" . $rs["order_id"]);
                        $this->fun->goods_update_log($rs["order_id"], "修改状态为：已支付<br>", 3);    //日志
                    }
                }
				if(count($result_orderID)>0)
				{
					$result_orderID = implode(",",$result_orderID);
					echo json_encode(array("code"=>200,"url"=>"/orderlist/orderlist?order_id={$result_orderID}"));
					die;
				}else{
					echo json_encode(array("code"=>201,"txt"=>'所选订单状态不对,不能修改为收款状态'));
					die;
				}
            }
			if ($type == 3)    //标配货
            {
                //判断必须都是已支付状态
                foreach ($reslist as $key => $rs) {
                    if ($rs["order_status"] == 2) {
						$result_usorderID[] = $rs["order_id"];	//存返回的订单ID号
                        $this->db->update("db_order_list", array("order_status" => 3), "order_id=" . $rs["order_id"]);
                        $this->fun->goods_update_log($rs["order_id"], "修改状态为：配货中<br>", 3);    //日志
                        //date 7/3    
                        $this->db->update('db_mabangorder', array("statusst" =>"配货中"), 'orderID=' ."'{$rs["order_sn"]}'");
                    }
                }
				if(count($result_usorderID)>0)
				{
					$result_usorderID = implode(",",$result_usorderID);
					echo json_encode(array("code"=>200,"url"=>"/orderlist/orderlist?order_id={$result_usorderID}"));
					die;
				}else{
					echo json_encode(array("code"=>201,"txt"=>'所选订单状态不对,不能修改为配货中状态'));
					die;
				}
                
            }
			if($type == 4)	//标发货
			{
				/*******手工标发货必须将数据存入db_mabang_scanorder 以记录发货报表信息****8-30**/
				//判断必须都是配货中状态
				$resultusorderID=array();
				$result_usorderIDstr=array();
                foreach ($reslist as $key => $rs) {
                    if ($rs["order_status"] ==3 && $rs["shipping_number"]) {
						$result_usorderIDstr[] = $rs["order_id"];	//存返回的订单ID号
						//预留遇到个SKU的商品，需要计算一个SKU的重量
						 //$ordersell = $this->db->get_where("db_order_sell","order_id=".$rs["order_id"])->result_array();
						 $skulist = $this->fun->getdatabasesdetail("db_order_sell"," AND order_id=".$rs["order_id"]," SUM(goods_number) as skunum");
						 $ordersell = $this->fun->getdatabasesdetail("db_order_sell"," AND order_id=".$rs["order_id"]," GROUP_CONCAT(goods_sn) as sku");
						
						
						//存出货记录
						if(intval($rs['actionorderweight'])==0)
						{
							$weight =  $rs['orderweight'];
						}else{
							$weight = $rs['actionorderweight'];
						}
						$postdata="";
						$postdata["batch_order_sn"] = $rs["order_sn"];
						$postdata["batch_shipping_number"] = $rs['shipping_number'];
						$postdata["batch_shipping_name"] = $rs["shipping_name"];
						$postdata["batch_orderweight"] = $weight;
						$postdata["oper"] = $_COOKIE["username"]?$_COOKIE["username"]:'郑超';
						$postdata["opertime"] = date("Y-m-d H:i:s");
						$postdata["yz"] = 0;
						$postdata["skuNum"] = $skulist['skunum'];
						$postdata["skulist"] = $ordersell['sku'];
						$this->db->insert("db_order_batchexpress",$postdata);
						 if($rs["shipping_status"]==3)	//EZGO美国仓，需要减库存
						 {
							  //自动减少库存
								 $ordersellList = $this->db->get_where("db_order_sell","order_id=".$rs["order_id"])->result_array();
								 if(count($ordersellList)>0)
								 {
									foreach($ordersellList as $key=>$resgoods)	//循环读取订单的销售列表
									{
										$this->fun->inventory($rs["order_id"],$resgoods["goods_id"],6,$resgoods["goods_number"],0);
									}
								 }
							
						 }else{
							$rval= "修改状态为：手工标发货不减库存 重量->{$weight} 运单号->{$rs[shipping_number]}<br>";
							$this->fun->goods_update_log($rs["order_id"], $rval, 3);    //日志
						 }


						
                        $this->db->update("db_order_list", array("order_status" => 4), "order_id=" . $rs["order_id"]);
                    }else{
						$resultusorderID[] = $rs["order_id"];	//存返回的订单ID号
					}
                }
				
				if(count($resultusorderID)>0)
				{
					$sums = count($resultusorderID);
					echo json_encode(array("code"=>201,"txt"=>"所选订单共[{$sums}]不是配货中或没有运单号,不能修改为已发货状态"));
					die;
				}else{
					$result_usorderIDstr = implode(",",$result_usorderIDstr);
					echo json_encode(array("code"=>200,"url"=>"/orderlist/orderlist?order_id={$result_usorderIDstr}"));
					die;
				}
				
			}
			if ($type == 5)    //标完成
            {
                //判断必须都是已发货
                foreach ($reslist as $key => $rs) {
                    if ($rs["order_status"] == 4) {
						$rorderID[] = $rs["order_id"];	//存返回的订单ID号
                        $this->db->update("db_order_list", array("order_status" => 5), "order_id=" . $rs["order_id"]);
                        $this->fun->goods_update_log($rs["order_id"], "修改状态为：已完成<br>", 3);    //日志
                    }
                }
				if(count($rorderID)>0)
				{
					$rorderID = implode(",",$rorderID);
					echo json_encode(array("code"=>200,"url"=>"/orderlist/orderlist?order_id={$rorderID}"));
					die;
				}else{
					echo json_encode(array("code"=>201,"txt"=>'选所订单状态不对,不能修改为已完成状态'));
					die;
				}
                
            }
			if ($type == 6)    //标作废
            {
                //判断必须都是已发货
                foreach ($reslist as $key => $rs) {
                    if ($rs["order_status"] != 5) {
                        //如果是海外仓订单，则海外仓也需撤单 1,2,3,4
                        if($rs['shipping_status']==1 || $rs['shipping_status']==2 || $rs['shipping_status']==3 ||$rs['shipping_status']==4){
                               $arr_oversea[] = $rs['order_sn'];
                        }

						$rerderID[] = $rs["order_id"];	//存返回的订单ID号
                        $this->db->update("db_order_list", array("order_status" =>6), "order_id=" . $rs["order_id"]);
                        $this->fun->goods_update_log($rs["order_id"], "修改状态为：作废<br>", 3);    //日志
                    }
                }
                 if(count($rerderID)>0)
				{
					$rerderID = implode(",",$rerderID);
                    if(count($arr_oversea)>0){
                        $overseaID = implode(",",$arr_oversea);
                        echo json_encode(array("code"=>200,"url"=>"/orderlist/orderlist?order_id={$rerderID}","overseaID"=>$overseaID));
                    }else{
                        echo json_encode(array("code"=>200,"url"=>"/orderlist/orderlist?order_id={$rerderID}"));
                    }

					die;
				}else{
					echo json_encode(array("code"=>201,"txt"=>'选所订单状态不对,不能修改为作废状态'));
					die;
				}
            }

        }
		
		/*****************
         ** 从待审核订单修改成正式订单
         ** $id int
         *************/
		if($op =='YesOrderData')
		{
			$order_id  = intval($this->input->post('order_id'));
			$rsdb = $this->db->get_where("db_order_sell","order_id='".$order_id."'")->result_array();
			foreach($rsdb as $key=>$rs)
			{
				$goods = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".$rs["goods_sn"]."'");
				$costprice = $this->fun->get_Goods_costprice($goods["goods_sku"]);//获取商品成本
				if($goods)
				{
					$post="";
					$post["goods_id"] = $goods["goods_id"];
					$post["costprice"] = $costprice;
					$post["goods_weight"] = $goods["g_weight"];
					$this->db->update("db_order_sell",$post,"rec_id='".$rs["rec_id"]."'");
				}
				
			}

			$this->db->update("db_order_list",array("order_status"=>2),"order_id='".$order_id."'");
			$this->order->recalculategoodsprice($order_id);//重新计算成本
			$this->fun->goods_update_log($order_id, "订单修改：SKU维护完成！导入订单流程<br>", 3);    //SKU维护完成！导入订单流程
		}
		
		/*****************
         ** 待审核订单添加新的商品信息
         ** $id int
         *************/
		if($op =='addnewgoods')
		{
			$goodsno = $this->input->post('goodsno');
			$goodsnostr = explode("-",$goodsno);
			$good_sku = $goodsnostr[0];
			$goodsparent = $this->fun->getdatabasesdetail("db_goods_parent"," AND p_parent_sku='".$good_sku."'");
			if($goodsparent["p_parent_id"])
			{
				$goodslist =  $this->db->get_where("db_goods", " goods_parentID  = '" . $goodsparent["p_parent_id"] . "'")->result_array();
				echo json_encode(array("code"=>202,"goods"=>$good_sku,"parentID"=>$goodsparent["p_parent_id"],"goodslist"=>$goodslist));
				die;
			}else{
				//没有，直接添加新的SKU
				echo json_encode(array("code"=>201,"goods"=>$good_sku));
				die;
			
			}
			print_r($goodsparent);
			die;
		}

		if($op=='getshoplist')
		{
			/********************************************
			* 获取店铺json
			***********************************************/
			$platformID  =intval($this->input->post('platformID'));
			if($platformID=="0")
			{
			$goodslist =  $this->db->get_where("d_shop", "  del_flag = 0")->result_array();
			}else{
			$goodslist =  $this->db->get_where("d_shop", " platfrom  = '" . $platformID . "' AND del_flag = 0")->result_array();
			}
			echo json_encode($goodslist);
			die;
		}
        /*****************
         ** 验证标签，是否交运   订单列表界面，打印订单标签
         ** $str  string
         *************/
        if ($op == 'printLabel') {
            $str = trim($this->input->post('str'),",");
            //$str_con = "(".trim($str,',').")";
            $arr_str = explode(",",$str);
            $str_con = "(";
            $str_str = "";
            foreach($arr_str as $key=>$value){
                //$str_con.= "'".$value."'".",";
                $str_str.= "'".$value."'".",";
            }
            $str_str .= trim($str_str,",");
            $str_con .=trim($str_str,",");
            $str_con.=")";
            $order_count = count(explode(",",$str_str));
            $sql = "SELECT a.order_id,b.orderType,b.id FROM db_order_list a LEFT JOIN db_mabangorder b ON a.order_sn = b.orderID AND a.shipping_number = b.mailNo WHERE a.shipping_name <>'' AND a.shipping_number <>'' AND a.order_sn in $str_con ";
            $rs = $this->db->query($sql)->result_array();
            //$arr_ret=array('txt'=>200,'url'=>count($arr_str),'msg'=>"有未交运订单!");
            ///echo json_encode($arr_ret);exit;
            $str_order_id = "";
            foreach($rs as $k=>$v){
                $str_order_id.=$v["id"].",";
            }
            $arr_orderType = array(3,4,5,10,12); //1顺丰2UPS3DHL4CNE5UBI6云途7燕文8EMS9无忧,10义达物流,11cnpost
            if(count($rs) == count($arr_str)){
                if($rs[0]['orderType']==11){
                     //跟e邮宝线下上海同一个模板
                    $url = "/order/ajaxbutton?op=sfexpressurl&orderType=8&id=".$str_order_id;
                    //$url = "/order/ajaxbutton?op=sfexpressurl&orderType=7&id=".$str_order_id; //根燕文同一个模板
                }elseif ($rs[0]['orderType']==8){
                    $url = "/order/ajaxbutton?op=sfexpressurl&orderType=8&id=".$str_order_id; //E邮宝线下上海
                }
                elseif(in_array($rs[0]['orderType'],$arr_orderType)){
                    $orderType = $rs[0]['orderType'];
                    $url = "/expressshipment/ajaxbutton?op=printlabel&orderType=$orderType&id=".$str_order_id; //另外一个模板
                }else{
                    $url = "/order/ajaxbutton?op=sfexpressurl&orderType={$rs[0]['orderType']}&id=".$str_order_id;
                }
                $arr_ret=array('txt'=>200,'url'=>$url,'msg'=>'');
            }else{
                $arr_ret=array('txt'=>201,'url'=>'','msg'=>"有未交运订单!");
            }
            echo json_encode($arr_ret);
            exit;
        }

        //订单交运是判断是否分仓
        if($op=='doSeparateWarehouse'){
            $str_orders = trim($this->input->post('str'),",");
            $sql = "SELECT * FROM db_order_list WHERE order_sn in ($str_orders) AND shipping_status = 0 ";
            $rs  = $this->db->query($sql)->result_array();
            if(count($rs)>0){ //有未分仓订单
                $data = array('code'=>201,'msg'=>"有未分仓订单");
            }else{
                $data = array('code'=>200,'msg'=>"所选择订单都已分仓");
            }
            echo json_encode($data);exit;
        }

    }
}
